package com.example.servlet;
import com.example.dao.UserDao;
import com.example.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (userDao.validateUser(username, password)) {
            // 登录成功
            User user = userDao.findByUsername(username);
            HttpSession session = req.getSession();
            session.setAttribute("user", user);

            // 重定向到成功页面
            resp.sendRedirect(req.getContextPath() + "/success.jsp");
        } else {
            // 登录失败
            req.setAttribute("error", "用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
